<template>
    <el-button type="success" @click="dialogVisible = true">新增</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="编号" width="150" />
    <el-table-column prop="roleName" label="角色名称" width="120" >
      <template v-slot="scope">
        <el-button link @click="openrole(scope.row)">{{ scope.row.roleName }}</el-button>
      </template>
    </el-table-column>
     <el-table-column prop="createName" label="创建人" width="120" />
    <el-table-column prop="createTime" label="创建日期" width="170" >
        <template v-slot="scope">
            <span>{{ moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人" width="120" />
    <el-table-column prop="updateTime" label="修改日期" width="170" >
        <template v-slot="scope">
            <span v-if="scope.row.updateTime==null"></span>
            <span v-else>{{ moment(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template v-slot="scope">
        <el-button link type="primary" size="small" @click="eidt(scope.row)">修改</el-button>
        <el-button link type="primary" size="small" @click="delrole(scope.row.id)">删除</el-button>
         <el-button link type="primary" size="small" @click="fenpei(scope.row)">分配人员</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增角色 -->
  <el-dialog
    v-model="dialogVisible"
    title="新增角色"
    width="500"
  >
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="ruleForm.roleName" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
  <!-- 修改角色 -->
  <el-dialog
    v-model="dialogVisibles"
    title="修改角色"
    width="500"
  >
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForms"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="ruleForms.roleName" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForms(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
  <!-- 分配人员 -->
   <el-dialog
    v-model="dialogVisibleshu"
    :title="'请设置【'+chuanrolename+'】角色的员工'"
    width="500"
  >
  <el-row>
    <el-col :span="12">
      <el-tree
    ref="treeRef"
    style="max-width: 600px"
    class="filter-tree"
    :data="data"
    :props="defaultProps"
    default-expand-all
    :filter-node-method="filterNode"
    @node-click="nodeclick"
  />
  </el-col>
    <el-col :span="6">
      <div>
        <tr>
     
            <el-checkbox-group v-model="roleuser" >
              <el-checkbox v-for="a in data1"  :value="a.id">
                {{ a.userName }}
              </el-checkbox>
            </el-checkbox-group>
        </tr>
      </div>
     
      
    </el-col>
  </el-row>
  <div>
    <tr>
  <td></td>
  <td>
      <el-button style="float: right;" type="primary" @click="CreatedelRolename">保存</el-button>
  </td>
 </tr>
  </div>
 
     
  </el-dialog>
  <!-- 角色名称弹出框 -->
  <el-dialog
    v-model="dialogVisiblerole"
    :title="'属于【'+chuanrolenames+'】角色的员工如下'"
    width="500"
  >
    
    <table>
      <tr v-for="item in getrolename.username1">
        <td>
          {{ item.userName }}
          <el-button @click="deluserrole(item.id)" style="width: 10px;height: 25px;border: none;font-size: 30px;">⨉</el-button>
        </td>
      </tr>
      <tr>
        <td><el-button @click="openfen()" style="width: 10px;height: 25px;border: none;font-size: 30px;">+</el-button></td>
      </tr>
        
    </table>
  </el-dialog>
</template>

<script lang="ts" setup>
import axios from 'axios';
import moment from 'moment';
import { onMounted, ref } from 'vue';
import read from '../../http/AxiosHelper';
import write from '../../http/AxiosHelper1';
onMounted(()=>{
    getrole();
})
//角色获取方法
const tableData =ref([]);
const getrole=()=>{
    read.get("/api/Role/GetRole").then(res=>{
        tableData.value=res.data.data;
    })
}
//添加角色弹出框
const dialogVisible=ref(false);
import { reactive} from 'vue'
import { ElMessage, type FormInstance, type FormRules,ElMessageBox  } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  roleName: '',
})
const locationOptions = ['Home', 'Company', 'School']
const rules = reactive({
  roleName: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
  ],
})
//添加角色方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      write.post("/api/Role/AddRole",ruleForm).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.msg);
            dialogVisible.value=false;
            ruleForm.roleName="";
            getrole();
        }
        else{
            ElMessage.error(res.data.msg);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//修改弹出框
const dialogVisibles=ref(false);
const ruleForms = reactive({
  id:'id',
  roleName: '',
})
//角色信息反填
const eidt=(row:any)=>{
    dialogVisibles.value=true;
    ruleForms.id=row.id;
    ruleForms.roleName=row.roleName;
}
//角色信息修改
const submitForms = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      write.put("/api/Role/UpdateRole",ruleForms).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.msg);
            dialogVisibles.value=false;
            ruleForms.roleName="";
            getrole();
        }
        else{
            ElMessage.error(res.data.msg);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//角色信息删除
const delrole=(id:any)=>{
    ElMessageBox.confirm(
    '确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     write.put("/api/Role/DelRole",{id:id}).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.msg);
            getrole();
        }
        else{
            ElMessage.error(res.data.msg);
        }
     })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
//部门树形
const dialogVisibleshu=ref(false);
import {  watch } from 'vue'
import type { FilterNodeMethodFunction, TreeInstance } from 'element-plus'
interface Tree {
  [key: string]: any
}
const filterText = ref('')
const treeRef = ref<TreeInstance>()
const defaultProps = {
  children: 'children',
  label: 'label',
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
//树形点击事件
const nodeclick=(x:any)=>{
    console.log(x);
    getshuuser(x.id);
}
//部门树形
const data: Tree[] = [
  {
    id: 0,
    label: '请选择部门',
    children: [
      {
        id: 1,
        label: 'IT信息部',
      },
       {
        id: 2,
        label: '人力资源部',
      },
       {
        id: 3,
        label: '财务部',
      },
       {
        id: 4,
        label: '销售部',
      },
    ],
  },

]
//根据部门id查询用户
const data1:any=ref([]);
const getshuuser=(id:any)=>{
    read.get("/api/User/GetBufenUser",{params:{Bid:id}}).then(res=>{
        data1.value=res.data.data;
    })
}
//分配人员按钮
const chuanrolename=ref('');
const fenpei=(row:any)=>{
    dialogVisibleshu.value=true;
    chuanrolename.value=row.roleName;
    getrolename.value.roleId=row.id;
    GetRoleUserId();
}
//分配人员添加
const getrolename=ref({
  "userId":[],
  "roleId":0,
  username1:[{
    "id":0,
    "userName":"",
  }]
})
const roleuser=ref([])
const CreatedelRolename=()=>{
  getrolename.value.userId=roleuser.value;
  write.post("/api/Role/AddUserRole",getrolename.value).then(res=>{
    if(res.data.code==200){
      ElMessage.success(res.data.msg);
      dialogVisibleshu.value=false;
      GetRoleUserId();
      getrole();
    }
    else{
      ElMessage.error(res.data.msg);
    }
  })
}
//根据角色id获取用户id
const GetRoleUserId=()=>{
  read.get("/api/Role/GetUserRole",{params:{RoleId
:getrolename.value.roleId}}).then(res=>{
    roleuser.value=res.data.data.map((item:any)=>Number(item.id));
    getrolename.value.username1=res.data.data;
    console.log(roleuser.value);

  })
}
//角色人员弹出框
const dialogVisiblerole=ref(false);
const chuanrolenames=ref([]);
//打开角色人员弹出框
const openrole=(row:any)=>{
  dialogVisiblerole.value=true;
  getrolename.value.roleId=row.id;
  chuanrolenames.value=row.roleName;
   chuanrolename.value=row.roleName;
  GetRoleUserId();
}
//删除角色相关人员
const deluserrole=(id:any)=>{
   write.post("/api/Role/DelUserRole",{
    "roleId":getrolename.value.roleId,
    "userId":id
   }).then(res=>{
    if(res.data.code==200){
      ElMessage.success(res.data.msg);
      GetRoleUserId();
      
    }
    else{
      ElMessage.error(res.data.msg);
    }
   })
}
//跳转到分配弹出框
const openfen=()=>{
  dialogVisibleshu.value=true;
}
</script>
